"""抖音数据源处理模块"""
import json
import os
from typing import Optional, Dict, Any
from aiohttp import web

from embytools.emby_client import EmbyClient
from embytools.douyin_exporter import export_emby_library_to_douyin_json
from dashboard.data_manager import DataManager

router = web.RouteTableDef()

# Emby客户端实例，将在main.py中注入
emby_client: Optional[EmbyClient] = None

# 数据管理器实例，将在main.py中注入
data_manager: Optional[DataManager] = None


def set_emby_client(client: EmbyClient):
    """设置Emby客户端实例"""
    global emby_client
    emby_client = client


def set_data_manager(manager: DataManager):
    """设置数据管理器实例"""
    global data_manager
    data_manager = manager


def load_config() -> Dict[str, Any]:
    """加载配置文件"""
    if data_manager:
        return data_manager.load_config() or {}
    return {}


def save_config(config: Dict[str, Any]) -> None:
    """保存配置文件"""
    if data_manager:
        data_manager.save_config(config)


@router.get("/douyin-sources")
async def douyin_sources_handler(request: web.Request):
    """抖音数据源页面"""
    html_content = '''
    <!DOCTYPE html>
    <html lang="zh-CN">
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>抖音数据源配置 - EmbyTools</title>
        <style>
            * {
                margin: 0;
                padding: 0;
                box-sizing: border-box;
            }
            body {
                font-family: Arial, sans-serif;
                background-color: #f5f5f5;
                color: #333;
            }
            .navbar {
                background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
                padding: 1rem 2rem;
                box-shadow: 0 2px 10px rgba(0,0,0,0.1);
            }
            .nav-container {
                max-width: 1200px;
                margin: 0 auto;
                display: flex;
                flex-direction: column;
                align-items: center;
            }
            
            /* 桌面端样式 */
            @media (min-width: 768px) {
                .nav-container {
                    flex-direction: row;
                    justify-content: space-between;
                }
            }
            .nav-title {
                color: white;
                font-size: 1.5rem;
                font-weight: bold;
                font-family: 'BM HANNA Pro OTF', sans-serif;
            }
            .nav-links {
                display: flex;
                gap: 2rem;
            }
            .nav-link {
                color: white;
                text-decoration: none;
                padding: 0.5rem 1rem;
                border-radius: 5px;
                transition: background-color 0.3s;
            }
            .nav-link:hover, .nav-link.active {
                background-color: rgba(255,255,255,0.2);
            }
            .container {
                max-width: 1200px;
                margin: 2rem auto;
                padding: 0 2rem;
            }
            .page-title {
                text-align: center;
                margin-bottom: 2rem;
                color: #333;
            }
            .content-container {
                background: white;
                border-radius: 8px;
                padding: 30px;
                box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
            }
            h1 {
                color: #2c3e50;
                margin-bottom: 30px;
                text-align: center;
            }
            .source-card {
                background: #f8f9fa;
                border: 1px solid #dee2e6;
                border-radius: 8px;
                padding: 20px;
                margin-bottom: 20px;
            }
            .source-header {
                font-size: 18px;
                font-weight: 600;
                margin-bottom: 15px;
                color: #495057;
            }
            .form-group {
                margin-bottom: 15px;
            }
            .form-group label {
                display: block;
                margin-bottom: 5px;
                font-weight: 500;
                color: #495057;
            }
            .form-group input[type="checkbox"] {
                margin-right: 10px;
            }
            .form-group select {
                width: 100%;
                padding: 8px 12px;
                border: 1px solid #ced4da;
                border-radius: 4px;
                font-size: 14px;
            }
            .btn {
                padding: 10px 20px;
                border: none;
                border-radius: 4px;
                font-size: 14px;
                cursor: pointer;
                transition: background-color 0.3s;
            }
            .btn-primary {
                background-color: #007bff;
                color: white;
            }
            .btn-primary:hover {
                background-color: #0056b3;
            }
            .btn-save {
                background-color: #28a745;
                color: white;
                margin-top: 20px;
                padding: 12px 30px;
                font-size: 16px;
            }
            .btn-save:hover {
                background-color: #218838;
            }
            .status-message {
                margin-top: 20px;
                padding: 15px;
                border-radius: 4px;
                display: none;
                transition: all 0.3s ease;
            }
            .status-success {
                background-color: #d4edda;
                color: #155724;
                border: 1px solid #c3e6cb;
                display: block;
                border-left: 4px solid #28a745;
            }
            .status-error {
                background-color: #f8d7da;
                color: #721c24;
                border: 1px solid #f5c6cb;
                display: block;
                border-left: 4px solid #dc3545;
            }
            .status-info {
                background-color: #cce5ff;
                color: #004085;
                border: 1px solid #b8daff;
                display: block;
                border-left: 4px solid #007bff;
            }
            .loading {
                text-align: center;
                padding: 20px;
                color: #666;
            }
            .hidden {
                display: none;
            }
        </style>
    </head>
    <body>
        <nav class="navbar">
            <div class="nav-container">
                <div class="nav-title">Mocaca</div>
                <div class="nav-links">
                    <a href="/" class="nav-link" onclick="showHomePage(event)">媒体库</a>
                    <a href="#" class="nav-link" onclick="showPhonePage(event)">播放列表</a>
                    <a href="/douyin-sources" class="nav-link active">数据源</a>
                    <a href="/settings" class="nav-link">设置</a>
                </div>
            </div>
        </nav>
        
        <div class="container">
            <h1 class="page-title">抖音数据源配置</h1>
            <div class="content-container">
            
            <div id="loading" class="loading">加载中...</div>
            
            <form id="sources-form">
                <div id="sources-container"></div>
                
                <div class="source-card" style="margin-top: 30px; background-color: #e8f4f8; border-color: #b8daff;">
                    <div class="source-header">🔄 同步配置</div>
                    <div class="form-group">
                        <label>
                            <input type="checkbox" id="sync-enabled" name="sync-enabled">
                            启用定时同步
                        </label>
                    </div>
                    <div class="form-group">
                        <label for="sync-interval">同步间隔（小时）：</label>
                        <select id="sync-interval" name="sync-interval">
                            <option value="1">1小时</option>
                            <option value="3">3小时</option>
                            <option value="6">6小时</option>
                            <option value="12">12小时</option>
                            <option value="24" selected>24小时</option>
                            <option value="48">48小时</option>
                        </select>
                    </div>
                    <div style="color: #666; font-size: 14px; margin-top: 10px;">
                        <p>💡 提示：开启后将通过定时任务自动触发媒体库JSON数据的重新生成</p>
                    </div>
                </div>
                
                <div style="text-align: center; margin-top: 30px;">
                    <button type="submit" class="btn btn-save" id="save-config-btn">保存配置</button>
                    <button type="button" class="btn btn-primary" id="sync-now-btn" style="margin-left: 15px;">立即同步</button>
                </div>
            </form>
            
            <div id="status-message" class="status-message"></div>
            </div>
        </div>
        
        <script>
            // 页面导航函数
            function showHomePage(event) {
                event.preventDefault();
                window.location.href = '/';
            }
            
            function showPhonePage(event) {
                event.preventDefault();
                window.location.href = '/';
                // 等待页面加载完成后显示手机页面
                setTimeout(() => {
                    const phoneLink = document.querySelector('.nav-link[onclick="showPage(\\'phone\\')"]');
                    if (phoneLink && typeof showPage === 'function') {
                        phoneLink.click();
                    }
                }, 100);
            }
            document.addEventListener('DOMContentLoaded', async function() {
                try {
                    // 加载媒体库列表
                    const librariesResponse = await fetch('/api/libraries');
                    const librariesData = await librariesResponse.json();
                    
                    if (!librariesData.success) {
                        throw new Error('获取媒体库列表失败');
                    }
                    
                    // 过滤掉不需要的媒体库类型
                    const excludedTypes = ['music', 'playlists', 'boxsets'];
                    const videoLibraries = librariesData.libraries.filter(function(lib) {
                        // 不显示MUSIC、PLAYLISTS、BOXSETS类型的媒体库
                        return !excludedTypes.includes(lib.type.toLowerCase());
                    });
                    
                    // 加载当前配置
                    const configResponse = await fetch('/api/douyin-sources/config');
                    const configData = await configResponse.json();
                    
                    const sourcesContainer = document.getElementById('sources-container');
                    sourcesContainer.innerHTML = '';
                    
                    // 设置同步配置
                    if (configData.sync) {
                        document.getElementById('sync-enabled').checked = configData.sync.enabled || false;
                        document.getElementById('sync-interval').value = configData.sync.interval_hours || 24;
                    }
                    
                    // 生成数据源表单
                    if (configData.sources && configData.sources.length > 0) {
                        configData.sources.forEach(function(source, index) {
                            const sourceCard = document.createElement('div');
                            sourceCard.className = 'source-card';
                            sourceCard.innerHTML = `
                                <div class="source-header">${source.name}</div>
                                <div class="form-group" style="display: flex; align-items: center; justify-content: space-between;">
                                    <label>
                                        <input type="checkbox" name="source-${index}-enabled" ${source.enabled ? 'checked' : ''}>
                                        启用此数据源
                                    </label>
                                    <label>
                                        <input type="checkbox" name="source-${index}-only-portrait" ${source.only_portrait ? 'checked' : ''}>
                                        仅纵屏
                                    </label>
                                </div>
                                <div class="form-group">
                                    <label for="source-${index}-library">选择媒体库：</label>
                                    <select id="source-${index}-library" name="source-${index}-library">
                                        <option value="">请选择媒体库</option>
                                        ${videoLibraries.map(function(lib) {
                                            return `<option value="${lib.id}:${lib.name}" ${source.library_id === lib.id ? 'selected' : ''}>${lib.name}</option>`;
                                        }).join('')}
                                    </select>
                                </div>
                                <input type="hidden" name="source-${index}-id" value="${source.id}">
                            `;
                            sourcesContainer.appendChild(sourceCard);
                        });
                    }
                    
                    // 隐藏加载状态
                    document.getElementById('loading').style.display = 'none';
                    
                } catch (error) {
                    console.error('加载失败:', error);
                    document.getElementById('loading').textContent = '加载失败，请刷新页面重试';
                }
            });
            
            // 保存配置
            document.getElementById('sources-form').addEventListener('submit', async function(e) {
                e.preventDefault();
                saveConfig();
            });
            
            // 立即同步按钮点击事件
            document.getElementById('sync-now-btn').addEventListener('click', async function() {
                await syncNow();
            });
            
            // 保存配置函数
            async function saveConfig() {
                try {
                    const formData = new FormData(document.getElementById('sources-form'));
                    const sources = [];
                    
                    // 获取所有数据源配置
                    let i = 0;
                    while (formData.has('source-' + i + '-id')) {
                        const libraryValue = formData.get('source-' + i + '-library') || '';
                        const parts = libraryValue.split(':') || ['', ''];
                        const libraryId = parts[0] || '';
                        const libraryName = parts[1] || '';
                        
                        sources.push({
                            enabled: formData.get('source-' + i + '-enabled') === 'on',
                            only_portrait: formData.get('source-' + i + '-only-portrait') === 'on',
                            id: formData.get('source-' + i + '-id'),
                            library_id: libraryId,
                            library_name: libraryName || (libraryId ? '未知媒体库' : '请选择媒体库'),
                            name: formData.get('source-' + i + '-id') === 'source1' ? '第1数据源' :
                                  formData.get('source-' + i + '-id') === 'source2' ? '第2数据源' : '第3数据源'
                        });
                        i++;
                    }
                    
                    // 准备同步配置
                    const syncConfig = {
                        enabled: formData.get('sync-enabled') === 'on',
                        interval_hours: parseInt(formData.get('sync-interval')) || 24
                    };
                    
                    // 保存配置
                    const response = await fetch('/api/douyin-sources/config', {
                        method: 'POST',
                        headers: {
                            'Content-Type': 'application/json'
                        },
                        body: JSON.stringify({ 
                            sources: sources,
                            sync: syncConfig
                        })
                    });
                    
                    const result = await response.json();
                    const statusMessage = document.getElementById('status-message');
                    
                    if (result.success) {
                        statusMessage.className = 'status-message status-success';
                        statusMessage.textContent = '配置保存成功！';
                    } else {
                        statusMessage.className = 'status-message status-error';
                        statusMessage.textContent = '保存失败: ' + (result.error || '未知错误');
                    }
                    
                    // 3秒后隐藏消息
                    setTimeout(function() {
                        statusMessage.className = 'status-message';
                    }, 3000);
                    
                } catch (error) {
                    console.error('保存失败:', error);
                    const statusMessage = document.getElementById('status-message');
                    statusMessage.className = 'status-message status-error';
                    statusMessage.textContent = '保存失败，请重试';
                }
            }
            
            // 立即同步函数
            async function syncNow() {
                try {
                    // 显示同步开始的消息
                    const statusMessage = document.getElementById('status-message');
                    statusMessage.className = 'status-message status-info';
                    statusMessage.textContent = '开始同步数据，请稍候...';
                    
                    // 先保存当前配置
                    await saveConfig();
                    
                    // 显示加载状态和临时消息
                    const syncBtn = document.getElementById('sync-now-btn');
                    const originalText = syncBtn.textContent;
                    syncBtn.disabled = true;
                    syncBtn.textContent = '同步中...';
                    
                    // 调用立即同步API
                    const response = await fetch('/api/douyin-sources/sync-now', {
                        method: 'POST',
                        headers: {
                            'Content-Type': 'application/json'
                        }
                    });
                    
                    const result = await response.json();
                    
                    if (result.success) {
                        statusMessage.className = 'status-message status-success';
                        statusMessage.textContent = result.message || '同步成功！';
                        
                        // 如果有导出结果，显示更详细的信息
                        if (result.export_results && result.export_results.length > 0) {
                            const successCount = result.export_results.filter(r => r.success).length;
                            const failedCount = result.export_results.filter(r => !r.success).length;
                            let details = [];
                            
                            result.export_results.forEach(item => {
                                if (item.success) {
                                    details.push(`${item.source_name}: 成功`);
                                } else {
                                    details.push(`${item.source_name}: 失败(${item.error || '未知错误'})`);
                                }
                            });
                            
                            // 创建详细信息显示
                            let detailsDiv = document.getElementById('sync-details');
                            if (!detailsDiv) {
                                detailsDiv = document.createElement('div');
                                detailsDiv.id = 'sync-details';
                                detailsDiv.style.marginTop = '15px';
                                detailsDiv.style.padding = '10px';
                                detailsDiv.style.backgroundColor = '#f5f5f5';
                                detailsDiv.style.borderRadius = '5px';
                                detailsDiv.style.maxHeight = '200px';
                                detailsDiv.style.overflowY = 'auto';
                                detailsDiv.style.fontSize = '14px';
                                statusMessage.parentNode.appendChild(detailsDiv);
                            }
                            
                            detailsDiv.innerHTML = `<strong>同步详情:</strong><br>${details.join('<br>')}`;
                            
                            // 5秒后隐藏详细信息
                            setTimeout(function() {
                                if (detailsDiv.parentNode) {
                                    detailsDiv.parentNode.removeChild(detailsDiv);
                                }
                            }, 5000);
                        }
                    } else {
                        statusMessage.className = 'status-message status-error';
                        statusMessage.textContent = '同步失败: ' + (result.error || '未知错误');
                    }
                    
                    // 恢复按钮状态
                    syncBtn.disabled = false;
                    syncBtn.textContent = originalText;
                    
                    // 3秒后隐藏消息
                    setTimeout(function() {
                        statusMessage.className = 'status-message';
                    }, 3000);
                    
                } catch (error) {
                    console.error('同步失败:', error);
                    const statusMessage = document.getElementById('status-message');
                    statusMessage.className = 'status-message status-error';
                    statusMessage.textContent = '同步失败，请重试';
                    
                    // 3秒后隐藏消息
                    setTimeout(function() {
                        statusMessage.className = 'status-message';
                    }, 3000);
                    
                    // 恢复按钮状态
                    const syncBtn = document.getElementById('sync-now-btn');
                    syncBtn.disabled = false;
                    syncBtn.textContent = '立即同步';
                }
            }
        </script>
    </body>
    </html>
    '''
    
    return web.Response(text=html_content, content_type='text/html', charset='utf-8')


@router.get("/api/douyin-sources/config")
async def get_douyin_sources_config(request: web.Request):
    """获取抖音数据源配置"""
    try:
        # 使用数据管理器获取抖音数据源配置（带缓存）
        douyin_sources = data_manager.get_douyin_sources()
        
        return web.json_response({
            'success': True,
            'sources': douyin_sources.get('sources', []),
            'enabled': douyin_sources.get('enabled', False),
            'sync': data_manager.get_sync_config()
        })
    except Exception as e:
        return web.json_response({
            'success': False,
            'error': str(e)
        })


@router.post("/api/douyin-sources/config")
async def save_douyin_sources_config(request: web.Request):
    """保存抖音数据源配置"""
    try:
        data = await request.json()
        
        # 保存抖音数据源配置
        douyin_config = {
            'sources': data.get('sources', []),
            'enabled': any(source.get('enabled', False) for source in data.get('sources', []))
        }
        data_manager.save_douyin_sources(douyin_config)
        
        # 更新同步配置
        if 'sync' in data:
            sync_config = {
                'enabled': data['sync'].get('enabled', False),
                'interval_hours': int(data['sync'].get('interval_hours', 24))
            }
            data_manager.save_sync_config(sync_config)
        
        return web.json_response({
            'success': True,
            'message': '配置保存成功'
        })
    except Exception as e:
        return web.json_response({
            'success': False,
            'error': str(e)
        })

@router.post("/api/douyin-sources/sync-now")
async def sync_douyin_sources_now(request: web.Request):
    """立即同步抖音数据源，生成JSON文件和7z文件"""
    try:
        # 添加详细日志
        print("=== 开始抖音数据源同步操作 ===")
        
        # 获取最新的数据源配置
        print("正在获取数据源配置...")
        douyin_sources = data_manager.get_douyin_sources()
        sources = douyin_sources.get('sources', [])
        enabled_sources = [s for s in sources if s.get('enabled', False) and s.get('library_id')]
        
        print(f"找到 {len(sources)} 个数据源，其中 {len(enabled_sources)} 个已启用")
        
        if not enabled_sources:
            error_msg = '没有启用的数据源，请先在配置中启用数据源'
            print(f"同步失败: {error_msg}")
            return web.json_response({
                'success': False,
                'error': error_msg
            })
        
        # 获取Emby配置
        print("正在获取Emby服务器配置...")
        config = data_manager.load_config()
        emby_config = config.get('server', {})
        emby_host = emby_config.get('host', 'localhost')
        emby_port = emby_config.get('port', 8096)
        emby_https = emby_config.get('https', False)
        api_key = emby_config.get('token', '')
        
        emby_server = f"{'https' if emby_https else 'http'}://{emby_host}:{emby_port}"
        print(f"Emby服务器: {emby_server}")
        
        if not api_key:
            error_msg = 'Emby API密钥未配置，请先在设置中配置Emby服务器信息'
            print(f"同步失败: {error_msg}")
            return web.json_response({
                'success': False,
                'error': error_msg
            })
        
        # 为每个启用的数据源生成JSON文件
        export_results = []
        # 定义文件名映射表
        filename_map = {
            0: 'first',
            1: 'second',
            2: 'third'
        }
        
        for index, source in enumerate(enabled_sources):
            source_name = source.get('name', f'数据源{source.get("id")}')
            library_id = source['library_id']
            # 根据索引获取文件名前缀，如果超出映射范围则使用默认命名
            file_prefix = filename_map.get(index, f'source_{library_id}')
            print(f"正在处理数据源: {source_name} (library_id: {library_id})，将生成 {file_prefix}.json")
            
            try:
                # 先删除旧文件（如果存在）
                json_file_path = os.path.join(r'./data/douyin', f'{file_prefix}.json')
                if os.path.exists(json_file_path):
                    os.remove(json_file_path)
                    print(f'已删除旧JSON文件: {json_file_path}')
                
                md_file_path = os.path.join(r'./data/douyin', f'{file_prefix}.md')
                if os.path.exists(md_file_path):
                    os.remove(md_file_path)
                    print(f'已删除旧MD文件: {md_file_path}')
                
                # 生成JSON数据，直接指定输出文件名
                print(f"正在为数据源 {source_name} 生成JSON文件...")
                result = await export_emby_library_to_douyin_json(
                    library_id=library_id,
                    library_name=source.get('library_name', 'Emby媒体库'),
                    emby_server=emby_server,
                    api_key=api_key,
                    only_portrait_videos=source.get('only_portrait', False),
                    output_filename=file_prefix  # 直接指定输出文件名（不含扩展名）
                )
                
                print(f"数据源 {source_name} JSON生成成功，导出 {result.get('video_count', 0)} 个视频")
                export_results.append({
                    'source_id': source.get('id'),
                    'source_name': source_name,
                    'success': True,
                    'result': result
                })
                
            except Exception as e:
                error_msg = f"数据源 {source_name} 处理失败: {str(e)}"
                print(error_msg)
                export_results.append({
                    'source_id': source.get('id'),
                    'source_name': source_name,
                    'success': False,
                    'error': str(e)
                })
        
        # 统计成功和失败的数量
        success_count = sum(1 for r in export_results if r['success'])
        failed_count = sum(1 for r in export_results if not r['success'])
        
        message = f'同步完成，成功 {success_count} 个，失败 {failed_count} 个'
        print(f"=== 同步操作完成: {message} ===")
        
        return web.json_response({
            'success': success_count > 0,
            'message': message,
            'export_results': export_results
        })
    except Exception as e:
        error_msg = f"同步过程发生异常: {str(e)}"
        print(error_msg)
        return web.json_response({
            'success': False,
            'error': error_msg
        })

@router.post("/api/douyin/generate-json")
async def generate_douyin_json_handler(request: web.Request):
    """生成抖音数据源JSON文件"""
    try:
        data = await request.json()
        source_id = data.get('source_id')
        
        # 获取数据源配置
        douyin_sources = data_manager.get_douyin_sources()
        sources = douyin_sources.get('sources', [])
        
        # 查找指定的数据源
        source = next((s for s in sources if s.get('id') == source_id), None)
        if not source:
            return web.json_response({
                'success': False,
                'error': f'数据源不存在: {source_id}'
            }, status=404)
        
        # 检查数据源是否有效
        if not source.get('enabled', False) or not source.get('library_id'):
            return web.json_response({
                'success': False,
                'error': '数据源无效或未启用'
            }, status=400)
        
        # 获取Emby配置
        config = data_manager.load_config()
        emby_config = config.get('server', {})
        emby_server = f"{'https' if emby_config.get('https', False) else 'http'}://{emby_config.get('host', 'localhost')}:{emby_config.get('port', 8096)}"
        api_key = emby_config.get('token', '')
        
        # 生成JSON数据
        # 注意：现在export_emby_library_to_douyin_json内部固定使用data/douyin目录
        result = await export_emby_library_to_douyin_json(
            library_id=source['library_id'],
            library_name=source.get('library_name', 'Emby媒体库'),
            emby_server=emby_server,
            api_key=api_key,
            only_portrait_videos=source.get('only_portrait', False)
        )
        
        return web.json_response({
            'success': True,
            'message': 'JSON生成成功',
            'result': result
        })
    except Exception as e:
        return web.json_response({
            'success': False,
            'error': str(e)
        }, status=500)